package com.zl.easybuy.service.impl;

import com.zl.easybuy.exception.EasyBuyException;
import com.zl.easybuy.mapper.OrderDetailMapper;
import com.zl.easybuy.mapper.OrderMapper;
import com.zl.easybuy.mapper.ProductMapper;
import com.zl.easybuy.mapper.UserAddressMapper;
import com.zl.easybuy.pojo.*;
import com.zl.easybuy.service.CartService;
import com.zl.easybuy.util.SessionUtils;
import com.zl.easybuy.util.ShoppingCart;
import com.zl.easybuy.util.ShoppingCartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 购物车业务类
 */
@Service
public class CartServiceImpl  implements CartService{
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;
    private UUID UUIDUtils;

    @Override
    public boolean addCart(Integer entityId, Integer quantity) throws EasyBuyException {
        ShoppingCart cart = SessionUtils.getCurrentCart();
        if(cart == null){
            cart = new ShoppingCart();
            SessionUtils.setCartInSession(cart);
        }
        //判断添加到购物车的数量是否比库存大   根据商品id 到数据库查询该商品
        Product product = productMapper.queryById(entityId);
        if(quantity > product.getStock()){  //数量大于库存
            throw new  EasyBuyException("商品数量不足");
        }
        //获取购物车中的所有的购物选项
        List<ShoppingCartItem> items = cart.getItems();
        if(!CollectionUtils.isEmpty(items)){
            //判断购物车中是否包含这个商品
            for(ShoppingCartItem item:items){
                if(item.getProduct().getId().intValue() == entityId.intValue()){ //存在该商品
                    int count = item.getQuantity() + quantity;  //修改后的数量
                    if(count > product.getStock() ){   //修改后的数量 大于库存
                        throw new  EasyBuyException("商品数量不足");
                    }else{
                        item.setQuantity(count); //修改数量
                        return true;
                    }
                }
            }
        }
        //没有该商品,创建购物选项
        ShoppingCartItem item = new ShoppingCartItem();
        item.setProduct(product);
        item.setQuantity(quantity);
        items.add(item);
        return true;
    }

    @Override
    public boolean modifyCart(Integer entityId, Integer quantity) throws EasyBuyException {
        ShoppingCart cart = SessionUtils.getCurrentCart();
        if (cart == null) {
            cart = new ShoppingCart();
            SessionUtils.setCartInSession(cart);
        }
        //判断添加到购物车的数量是否比库存大   根据商品id 到数据库查询该商品
        Product product = productMapper.queryById(entityId);
        if (quantity > product.getStock()) {  //数量大于库存
            throw new EasyBuyException("商品数量不足");
        }
        //获取购物车中的所有的购物选项
        List<ShoppingCartItem> items = cart.getItems();
        if (!CollectionUtils.isEmpty(items)) { //不是空
            //判断购物车中是否包含这个商品
            for (ShoppingCartItem item : items) {
                if (item.getProduct().getId().intValue() == entityId.intValue()) { //存在该商品
                    if(quantity > 0){
                        item.setQuantity(quantity); //修改数量
                    }else{  //等于0
                        //删除
                        items.remove(item);
                    }
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Order settlementCart(Integer addressId, String newAddress, String newRemark) throws EasyBuyException{
       //c从session中获取购物车
        ShoppingCart currentCart = SessionUtils.getCurrentCart();
        //获取当前登录的用户信息
        User currentUser = SessionUtils.getCurrentUser();
        //检查库存是否大于等于购买的数量，每一个商品
        if(!checkStock(currentCart)){
            //如果不满足，抛异常
            throw new EasyBuyException("库存数量不足");
        }
        //如果满足，执行
        //判断是否添加新地址，easybuy_user_address表添加记录
        UserAddress userAddress = new UserAddress();
        if(addressId.intValue()==-1){
            if(newAddress == null || newAddress.trim().isEmpty()){//没有传递地址
                throw new EasyBuyException("请输入地址");
            }else {
                userAddress.setAddress(newAddress.trim());
                userAddress.setRemark(newRemark);
                userAddress.setUserId(currentUser.getId());
                userAddress.setCreateTime(new Date());
                userAddress.setIsDefault(1);
                userAddressMapper.add(userAddress);
            }
        }else{ //不用新的地址，根据地址id从数据库中查询地址
            userAddress = userAddressMapper.queryById(addressId);
        }
        //生成订单以及订单详细，保存到数据库
        Order order = new Order();
        order.setLoginName(currentUser.getLoginName());
        order.setCost(currentCart.getSum());
        order.setCreateTime(new Date());
        order.setSerialNumber(UUIDUtils.randomUUID());
        order.setUserAddress(userAddress.getAddress());
        order.setUserId(currentUser.getId());
        orderMapper.add(order);
        //生成订单详情，一个购物对应一个订单详情
        List<ShoppingCartItem> items = currentCart.getItems();
        for(ShoppingCartItem item:items){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderDetail.getId());
            orderDetail.setCost(item.getCost());
            orderDetail.setProductId(item.getProduct().getId());
            orderDetail.setQuantity(item.getQuantity());
            //保存数据到数据库中
            orderDetailMapper.add(orderDetail);
            //减少对应商品的库存数量
            productMapper.update(item.getProduct().getId(),item.getProduct().getStock(),item.getQuantity());

        }
        return order;
    }
      //检查购物车中的每一件商品的购买数量，小于等于库存允许购买
    private boolean checkStock(ShoppingCart currentCart){
        boolean flag = true;
        if(currentCart != null){
            List<ShoppingCartItem> items = currentCart.getItems();
            for(ShoppingCartItem item:items){
                if(item.getQuantity()>item.getProduct().getStock()){
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }
}
